#!/usr/bin/env python
#coding:utf-8

import urllib2
import urllib
import os
import imglister

imagepath = []

def cd(ss):
    try:
        os.chdir(ss)
        print '改变工作目录为:'+ss
        return 0
    except:
        print '输入图片保存路径有误，请重新输入'
        return 1

def addimagepath(surl):
    if 'http://' in surl:
        imagepath.append(surl)
        print '找到图片：'+surl.split('/')[-1]+'图片地址为：'+surl
    else:
        surl = str_url+surl
        imagepath.append(surl)
        print '找到图片：'+surl.split('/')[-1]+'图片地址为：'+surl

def imageDown(list_image):
    if not list_image:
        print '该页面没有任何图片'
    else:
        for image in list_image:
            try:
                urllib.urlretrieve(image, image.splib('/')[-1])
                print '来自'+image+'的图片保存成功！'
            except:
                print '来自%s的图片保存不成功，继续保存下一张...'%image

                print '请输入出图片的保存路径，如果直接回车将默认保存到我的文档'

                temp = 1
                while temp:
                    str_save = raw_input()
                    if not str_save:
                        str_save = '/home/wwq/photos'
                        temp = cd(str_save)

                        try:
                            sock = urllib2.urlopen(str_url)
                            print '页面连接成功！开始获取图片地址...'
                        except:
                            print 'Sorry, 输入的地址有误或页而无法连接，程序将自动退出！'

                        parser = IMGLister()
                        parser.feed(sock.read())
                        sock.close()
                        parser.close()
                        for url in parser.urls:
                            addimagepath(url)

if __name__ == '__main__':
    imageDown(imagepath)
                
    
